import type { FormInstance, Rule } from 'ant-design-vue/lib/form'
import type { Ref } from 'vue'

import { computed, unref } from 'vue'

export function useFormValid<T extends object = any>(formRef: Ref<FormInstance>) {
  async function validForm() {
    const form = unref(formRef)
    if (!form)
      return
    const data = await form.validate()
    return data as T
  }

  return { validForm }
}

export function useFormRules(formData?: Recordable) {
  const getAccountFormRule = computed(() => createRule('请输入账号'))
  const getPasswordFormRule = computed(() => createRule('请输入密码'))

  const getFormRules = computed((): { [k: string]: Rule | Rule[] } => {
    const accountFormRule = unref(getAccountFormRule)
    const passwordFormRule = unref(getPasswordFormRule)

    console.log(formData)
    return {
      username: accountFormRule,
      password: passwordFormRule,
    }
  })
  return { getFormRules }
}

function createRule(message: string): Rule[] {
  return [
    {
      required: true,
      message,
      trigger: 'change',
    },
  ]
}
